package com.gticket.customerbackend.handler;

import com.rabbitmq.client.Channel;
import io.swagger.annotations.Api;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeoutException;

/**
 * @author 李浩楠
 * @date 2019/11/29 下午12:18
 */
@Data
@RestController
@Slf4j
@Api(value = "提供给header的controller" , tags = "Header handler")
public class HeaderHandler {
    // 存信息,根据key值分发给不同的商户
    Map<String,List> messMap = new HashMap();


    @GetMapping("/getNotifyMsg")
    @ResponseBody
    public List getNotifyMsg(String db) {
        return messMap.get(db);
    }

    @GetMapping("/readNotifyMsg")
    @ResponseBody
    public void readNotifyMsg(String db) {
        messMap.put(db,null);
    }

    // 普通队列监听
    @RabbitListener(queues = "orderQueue")
    public void process5(Message message, Channel channel, String msg) {
        log.info(msg);
        String[] temp = new String(message.getBody()).split("\\.");
        System.out.println("===========" + temp[0]);
        System.out.println("===========" + temp[1]);

        if(messMap.get(temp[0]) != null){
            messMap.get(temp[0]).add(temp[1]);
        } else {
            List<String> NotifyMsg = new ArrayList<String>();
            NotifyMsg.add(temp[1]);
            messMap.put(temp[0],NotifyMsg);
        }
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            log.info("成功消费信息，返回到小铃铛。");
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                channel.close();
            } catch (IOException e) {

            } catch (TimeoutException e) {
                e.printStackTrace();
            }
        }
    }


}
